package com.seguriapp.administration.gwt.server;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.resource.ClientResource;

import com.seguriapp.administration.gwt.shared.ValidateUserDataAction;
import com.seguriapp.administration.gwt.shared.ValidateUserDataResult;
import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;

public class ValidateUserDataHandler extends AbstractSeguriAppHandler<ValidateUserDataAction, ValidateUserDataResult> {

  private static final Logger LOGGER = Logger.getLogger(ValidateUserDataHandler.class);

  public Class<ValidateUserDataAction> getActionType() {
    return ValidateUserDataAction.class;
  }

  public ValidateUserDataResult execute(final ValidateUserDataAction action, final ExecutionContext context) throws DispatchException {

    final ValidateUserDataResult result = new ValidateUserDataResult();
    try {
      final String url = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl()
          .concat(GlobalConfigLoader.getInstance().getGlobalConfig().getValidateUserData());
      final ClientResource resource = new ClientResource(url);
      final String errorMessage = resource.post(convertDataToJsonString(action)).getText();
      LOGGER.info("Data received : \n" + errorMessage);
      result.setErrorMessage(errorMessage);
    } catch (Exception e) {
      LOGGER.error("Error validating user data \n", e);
    }
    return result;
  }

  private String convertDataToJsonString(final ValidateUserDataAction action) {
    final JSONObject obj = new JSONObject();
    try {
      obj.put("username", action.getUsername());
      obj.put("isNewUser", action.isNewUser());
    } catch (JSONException e) {
      LOGGER.error("Error converting user data to json \n", e);
    }
    LOGGER.info("Sending Data : \n" + obj.toString());
    return obj.toString();
  }

}
